#############################################################################
##
## Copyright (C) 2006-2006 Mindcast Productions. All rights reserved.
##
## This file is part of the Universal SQL Navigator - UniSQLNav.
## Find more information in: http://code.google.com/p/unisqlnav/
## Contact at carlosedp@gmail.com
##
## This file may be used under the terms of the GNU General Public
## License version 2.0 as published by the Free Software Foundation
## and appearing in the file LICENSE.GPL included in the packaging of
## this file.  Please review the following information to ensure GNU
## General Public Licensing requirements will be met:
## http://www.gnu.org/licenses/gpl.txt
##
## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
##
## $Rev: $
## $Date: $
##
#############################################################################

from PyQt4 import QtCore, QtGui, Qsci

from utils import QTUtilities
from ui.internalWindow import internalWindowTemplate
from ui.ui_sqlwindow import Ui_SQLWindow
from db.backends import DBQueryError

class sqlWindow(internalWindowTemplate, Ui_SQLWindow):
    def __init__(self, parent, session=None, sessionname=None,object=None):
        internalWindowTemplate.__init__(self, parent)
        
        self.session = session
        if self.session and object:
            self.sqlEditor.setText("SELECT * FROM %s;" % object)
        self.setWindowTitle(self.windowTitle() + ' - ' + sessionname)
        self.connect(self.executeButton, QtCore.SIGNAL("clicked()"),self.executeSQL)
        self.connect(self.nextPageButton, QtCore.SIGNAL("clicked()"),self.nextPage)
        self.connect(self.allRowsButton, QtCore.SIGNAL("clicked()"),self.allRows)
        self.connect(self.dataTable, QtCore.SIGNAL("currentItemChanged (QTableWidgetItem *, QTableWidgetItem *)"),self.fetchNext)
        self.connect(self.dataTable, QtCore.SIGNAL("currentItemChanged (QTableWidgetItem *, QTableWidgetItem *)"),self.fetchNext)

        font = QtGui.QFont('Courier New', 10)
        lex = Qsci.QsciLexerSQL()
        lex.setDefaultFont(font)
        self.sqlEditor.setLexer(lex)
        self.sqlEditor.setAutoIndent(True)

        QTUtilities.makeMenuAction(self.sqlEditor, "Execute", self.executeAll, 'F9')
        QTUtilities.makeMenuAction(self.sqlEditor, "Execute Selected", self.executeSelected, 'F8')
        
    def executeSQL(self, type='all'):
        try:
            if type == 'all':
                self.cursor = self.session.queryDataCursor(str(self.sqlEditor.text()))
            elif type == 'selected':
                self.cursor = self.session.queryDataCursor(str(self.sqlEditor.selectedText()))
            self.populateTable()
        except DBQueryError, msg:
            QtGui.QMessageBox.critical( self, self.tr('Error'), str(msg),
                                        QtGui.QMessageBox.Ok,QtGui.QMessageBox.NoButton,QtGui.QMessageBox.NoButton)
            
    def executeAll(self):
        self.executeSQL(type='all')
        
    def executeSelected(self):
        self.executeSQL(type='selected')
 
    def populateTable(self):
       # Sets the table
        self.dataTable.setSortingEnabled(False)
        for row in range(self.dataTable.rowCount()):
            self.dataTable.removeRow(0)
        self.dataTable.verticalHeader().hide()

        columns = self.cursor.description
        tableColumns = [a[0] for a in columns]
        self.dataTable.setColumnCount(len(tableColumns))
        self.dataTable.setHorizontalHeaderLabels(tableColumns)
        for i in xrange(self.pageSize.value()):
            result = self.cursor.fetchone()
            if not result:
                break
            row = self.dataTable.rowCount()
            self.dataTable.insertRow(row)

            for col in range(self.dataTable.columnCount()):
                self.dataTable.setItem(row, col, QtGui.QTableWidgetItem(str(result[col])))

        self.dataTable.setSortingEnabled(True)
        self.dataTable.sortItems(0)
        self.dataTable.resizeColumnsToContents()
        self.dataTable.resizeRowsToContents()
        rows = str(self.dataTable.rowCount()) + " rows returned."
        self.statusbar.showMessage(rows)        

    def nextPage(self):
        self.dataTable.setSortingEnabled(False)
        for i in xrange(self.pageSize.value()):
            result = self.cursor.fetchone()
            if not result:
                return
            row = self.dataTable.rowCount()
            self.dataTable.insertRow(row)

            for col in range(self.dataTable.columnCount()):
                self.dataTable.setItem(row, col, QtGui.QTableWidgetItem(str(result[col])))
        self.dataTable.setSortingEnabled(True)
        self.dataTable.resizeColumnsToContents()
        self.dataTable.resizeRowsToContents()
        rows = str(self.dataTable.rowCount()) + " rows returned."
        self.statusbar.showMessage(rows)
        
    def allRows(self):
        self.dataTable.setSortingEnabled(False)
        result = self.cursor.fetchall()
        if not result:
            return
        for item in result:
            row = self.dataTable.rowCount()
            self.dataTable.insertRow(row)
            for col in range(self.dataTable.columnCount()):
                self.dataTable.setItem(row, col, QtGui.QTableWidgetItem(str(item[col])))
        
        rows = str(self.dataTable.rowCount()) + " rows returned."
        self.statusbar.showMessage(rows)        
        self.dataTable.setSortingEnabled(True)
        self.dataTable.resizeColumnsToContents()
        self.dataTable.resizeRowsToContents()

    def fetchNext(self, item, previtem):
        last = self.dataTable.rowCount()
        if item.row() == last-1:
            self.dataTable.setSortingEnabled(False)
            self.dataTable.insertRow(last)
            result = self.cursor.fetchone()
            for col in range(self.dataTable.columnCount()):
                self.dataTable.setItem(last, col, QtGui.QTableWidgetItem(str(result[col])))
            self.dataTable.setSortingEnabled(True)
            self.dataTable.resizeColumnsToContents()
            self.dataTable.resizeRowsToContents()

    
    
    